package cn.itcast.controller;

import cn.itcast.constant.MessageConstant;
import cn.itcast.entity.PageResult;
import cn.itcast.entity.QueryPageBean;
import cn.itcast.entity.Result;
import cn.itcast.pojo.Menu;
import cn.itcast.pojo.User;
import cn.itcast.service.UserService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("user")
@CrossOrigin
public class UserController {

    private final BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

    @Reference
    private UserService userService;

    //获得当前登录用户的用户名
    @RequestMapping("/getUsername")
    public Result getUsername() {
        //当Spring security完成认证后，会将当前用户信息保存到框架提供的上下文对象
        org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println(user);
        if (user != null) {
            String username = user.getUsername();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, username);
        }

        return new Result(false, MessageConstant.GET_USERNAME_FAIL);
    }

    /**
     * 查找用户列表（可带参数搜索）
     *
     * @return {@link Result}
     */
    @GetMapping("page")
    public Result findPermission(QueryPageBean queryPageBean) {
        try {
            PageResult result = userService.findUser(queryPageBean.getCurrentPage(), queryPageBean.getPageSize(), queryPageBean.getQueryString());
            return new Result(true, MessageConstant.QUERY_USER_SUCCESS, result);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_USER_FAIL);
        }
    }

    /**
     * 更新用户
     *
     * @param roleIds 角色id
     * @param user    用户
     * @return {@link Result}
     */
    @PutMapping()
    public Result updateUser(@RequestParam("roleIds") Integer[] roleIds,
                             @RequestBody User user) {
        try {
            userService.updateUser(roleIds, user);
            return new Result(true, MessageConstant.EDIT_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_USER_FAIL);
        }
    }

    /**
     * 添加用户
     *
     * @param roleIds 角色id
     * @param user    用户
     * @return {@link Result}
     */
    @PostMapping()
//    @PreAuthorize("hasAuthority('USER_ADD')")
    public Result addUser(@RequestParam("roleIds") Integer[] roleIds,
                          @RequestBody User user) {
        try {
            user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
            userService.addUser(roleIds, user);
            return new Result(true, MessageConstant.ADD_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_USER_FAIL);
        }
    }

    /**
     * 查询单个用户信息
     *
     * @param userId 用户id
     * @return {@link Result}
     */
    @GetMapping("{id}")
    public Result findOneUser(@PathVariable("id") Integer userId) {
        try {
            User user = userService.findOneUser(userId);
            return new Result(true, MessageConstant.QUERY_USER_SUCCESS, user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_USER_FAIL);
        }
    }

    /**
     * 通过用户id查询相关联的角色id
     *
     * @return {@link Result}
     */
    @GetMapping("{id}/roleIds")
    public Result findRoleIdsByUserId(@PathVariable("id") Integer id){
        try {
            List<Integer> list = userService.findRoleIdsByUserId(id);
            return new Result(true, MessageConstant.QUERY_USER_SUCCESS, list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_USER_FAIL);
        }
    }

    /**
     * 删除权限的id
     *
     * @param id id
     * @return {@link Result}
     */
    @DeleteMapping("{id}")
//    @PreAuthorize("hasAuthority('USER_DELETE')")
    public Result deletePermissionById(@PathVariable("id") Integer id) {
        try {
            boolean bool = userService.deleteUserById(id);
            if (bool) {
                return new Result(true, MessageConstant.DELETE_USER_SUCCESS);
            }
            return new Result(false, MessageConstant.DELETE_USER_FAIL_1);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_USER_FAIL);
        }
    }

    /**
     * 查询用户能控制的菜单
     *
     * @return {@link Result}
     */
    @GetMapping("/menuList")
    public Result findUserMenu() {
        try {
            org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            List<Menu> list =userService.findMenuByUsername(user.getUsername());
            return new Result(true, MessageConstant.QUERY_MENU_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_MENU_FAIL);
        }
    }
}
